package com.bzsg.simpleMediaPlayer.ui.pager.thumbnail

import android.content.Intent
import android.graphics.Bitmap
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.bzsg.simpleMediaPlayer.PlayerActivity
import com.bzsg.simpleMediaPlayer.data.VideoItem
import com.bzsg.simpleMediaPlayer.data.VideoUiState
import com.bzsg.simpleMediaPlayer.viewModel.VideoViewModel

@Composable
fun VideoGalleryScreen(viewModel: VideoViewModel = hiltViewModel()) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    LaunchedEffect(Unit) {
        viewModel.loadVideos()
    }

    Box(modifier = Modifier.fillMaxSize()) {
        when (val state = uiState) {
            is VideoUiState.Loading -> Text("load")
            is VideoUiState.Success ->
                VideoGrid(
                    viewModel = viewModel,
                    videos = state.videos,
                    thumbnailMap = state.thumbnailMap,
                )

            is VideoUiState.Error -> Text("error")
        }
    }
}

@Composable
private fun VideoGrid(
    viewModel: VideoViewModel,
    videos: List<VideoItem>,
    thumbnailMap: Map<Long, Bitmap>,
) {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 120.dp),
        modifier = Modifier.padding(8.dp),
    ) {
        items(items = videos, key = { it.id }) { video ->
            VideoThumbnailCard(viewModel = viewModel, video = video, thumbnailMap = thumbnailMap)
        }
    }
}

@Composable
private fun VideoThumbnailCard(
    viewModel: VideoViewModel,
    video: VideoItem,
    thumbnailMap: Map<Long, Bitmap>,
) {
    // 优先使用预加载的缩略图
    val cachedBitmap =
        remember(video.id) {
            mutableStateOf(thumbnailMap[video.id])
        }
    val context = LocalContext.current
    // 按需加载未缓存的缩略图
    LaunchedEffect(video.id) {
        if (cachedBitmap.value == null) {
            cachedBitmap.value = viewModel.loadThumbnail(context, video.id)
        }
    }
    Card(
        modifier =
            Modifier
                .padding(4.dp)
                .fillMaxWidth().clickable {
                    // 创建跳转 Intent
                    val intent =
                        Intent(context, PlayerActivity::class.java).apply {
                            putExtra("MEDIA_ID_EXTRA", video.id) // 传递媒体ID
                            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        }
                    context.startActivity(intent)
                }
                .padding(16.dp),
    ) {
        Column {
            // Coil 加载视频缩略图
            AsyncImage(
                model = cachedBitmap.value,
                contentDescription = video.name,
                modifier =
                    Modifier
                        .fillMaxWidth()
                        .aspectRatio(16f / 9f),
                contentScale = ContentScale.Crop,
            )

            // 视频信息
            Text(
                text = video.name,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.padding(8.dp),
            )
            Row(
                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
            ) {
                Text(video.duration, fontSize = 12.sp)
                Text("${video.size / 1024}KB", fontSize = 12.sp)
            }
        }
    }
}
